package com.training.bt.schedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.training.bt.entity.PeerActivity;
import com.training.bt.entity.UserPoint;
import com.training.bt.mapper.PeerActivityMapper;
import com.training.bt.mapper.UserPointMapper;
import com.training.bt.service.PointsRecordService;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class SeedingPointScheduler {

    @Autowired
    private PeerActivityMapper peerActivityMapper;
    
    @Autowired
    private UserPointMapper userPointMapper;

    @Autowired
    private PointsRecordService pointsRecordService;    

    // 每天凌晨00:00执行
    @Scheduled(cron = "0 0 0 * * ?")
    public void calculateDailySeedingPoints() {
        // 1. 获取所有正在做种且未停止的记录
        List<PeerActivity> seedingActivities = peerActivityMapper.selectList(
            new LambdaQueryWrapper<PeerActivity>()
                .eq(PeerActivity::getIsSeeding, true)
                .isNotNull(PeerActivity::getSeedingStartTime)
        );

        // 2. 遍历处理每个做种记录
        seedingActivities.forEach(activity -> {
            LocalDateTime lastStart = activity.getSeedingStartTime();
            LocalDateTime now = LocalDateTime.now();
            
            // 计算时间差（秒）
            long seconds = Duration.between(lastStart, now).getSeconds();
            int points = (int) (seconds / 1800); // 每30分钟=1分
            
            if (points > 0) {
                // 3. 更新用户积分
                UserPoint userPoint = userPointMapper.findByUserId(activity.getUserId());
                userPoint.setPoint(userPoint.getPoint() + points);
                userPointMapper.updateById(userPoint);
                
                // 4. 重置开始时间为当前结算时间（避免重复计算）
                activity.setSeedingStartTime(now); 
                peerActivityMapper.updateById(activity);

                pointsRecordService.pointsAdd(activity.getUserId(), points);
            }
        });
    }
}
